package com.springbootvue.Utils;

import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author yhz
 * @Data 13:02 2020/1/25
 */
public class ESApi {
    private static String index = "healthy";
    //创建REST高级客户端
    private static RestHighLevelClient client =  new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("localhost",9200,"http")
            ));

    public static void main(String[] args) throws IOException {
        SearchHits yhz = search2("Member_Name","yhz");
        SearchHit[] hits = yhz.getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            System.out.println(source);
        }
//        HashMap map = new HashMap();
//        map.put("id","2");
//        map.put("Member_ID","2");
//        map.put("Member_Name","zlc");
//        map.put("Member_Phone","15093318471");
//        map.put("Member_Address","河南郑州");
//        addDoc(map,"userinfo");
        client.close();
    }
    /*
     * type操作
     * */
    public static void addDoc(Map map,String types) throws IOException {

        IndexRequest indexRequest = new IndexRequest(index, types, String.valueOf(map.get("id"))).source(map);
        client.index(indexRequest);
        System.out.println("向服务器增加文档：");
    }


    //删除表
    private static void delDoc(Map map) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(index, "product", String.valueOf(map.get("id")));
        client.delete(deleteRequest);
        System.out.println("删除id为"+map.get("id")+"的文档");
    }

    //修改表
    private static void upDoc(Map map) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(index, "product", String.valueOf(map.get("id"))).doc("name", map.get("name"));
        client.update(updateRequest);
        System.out.println("更新文档为："+map);
    }

    //查询表
    private static void getDoc(int id) throws IOException {
        GetRequest getRequest = new GetRequest(index, "product", String.valueOf(id));
        GetResponse getResponse = client.get(getRequest);
        if(!getResponse.isExists()){
            System.out.println("id为"+id+"不存在");
        }else{
            String source = getResponse.getSourceAsString();
            System.out.println("id为"+id+"文档为：");
            System.out.println(source);
        }

    }

    /*
     * 索引操作
     * */
    //判断索引是否存在
    private static boolean checkExistIndex(String indexName) throws IOException {
        boolean rs = true;
        try {
            OpenIndexRequest openIndexRequest = new OpenIndexRequest(indexName);
            client.indices().open(openIndexRequest).isAcknowledged();
        }catch (ElasticsearchStatusException e){
            String m = "Elasticsearch exception [type=index_not_found_exception, reason=no such index]";
            if(m.equals(e.getMessage())){
                rs = false;
            }
        }
        if(rs){
            System.out.println("索引"+indexName+"存在");
        }else{
            System.out.println("索引"+indexName+"不存在");
        }
        return rs;
    }

    //删除索引
    private static void delIndex(String indexName) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        client.indices().delete(deleteIndexRequest);
    }

    //创建索引
    private static void createIndex(String indexName) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        client.indices().create(createIndexRequest);
        System.out.println("创建了索引"+indexName);
    }


    //条件查询
    private static SearchHits search(String keyword, int start, int count) throws IOException {

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        //条件查询
        MatchQueryBuilder matchBuilder = new MatchQueryBuilder("name", keyword);
        //模糊匹配
        matchBuilder.fuzziness(Fuzziness.AUTO);
        searchBuilder.query(matchBuilder);
        //几条
        searchBuilder.from(start);
        //几条
        searchBuilder.size(count);
        //匹配度
        searchBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        searchRequest.source(searchBuilder);
        SearchResponse search = client.search(searchRequest);
        SearchHits hits = search.getHits();
        return hits;
    }
    //条件查询2
    public static SearchHits search2(String text,String keyword) throws IOException {

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        //条件查询
        MatchQueryBuilder matchBuilder = new MatchQueryBuilder(text, keyword);
        //模糊匹配
        matchBuilder.fuzziness(Fuzziness.AUTO);
        searchBuilder.query(matchBuilder);
        //匹配度
        searchBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        searchRequest.source(searchBuilder);
        SearchResponse search = client.search(searchRequest);
        SearchHits hits = search.getHits();
        return hits;
    }

}
